import mysql from 'mysql2/promise'
import { DB_CONFIG } from './config'

export async function initDatabase() {
  const pool = mysql.createPool(DB_CONFIG)

  try {
    // 创建任务表
    await pool.execute(`
      CREATE TABLE IF NOT EXISTS tasks (
        id VARCHAR(36) PRIMARY KEY,
        type VARCHAR(50) NOT NULL,
        status VARCHAR(20) NOT NULL,
        files JSON NOT NULL,
        options JSON,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        result JSON
      )
    `)

    // 创建设置表
    await pool.execute(`
      CREATE TABLE IF NOT EXISTS settings (
        \`key\` VARCHAR(50) PRIMARY KEY,
        value TEXT NOT NULL
      )
    `)

    return pool
  } catch (error) {
    console.error('数据库初始化失败:', error)
    throw error
  }
}

let pool: mysql.Pool | null = null

export async function getPool() {
  if (!pool) {
    pool = await initDatabase()
  }
  return pool
} 